class_name Enemy
extends CharacterBody2D

@onready var body=$AnimatedSprite2D

var dir=null
var target=null

var level=1:
	set(v):
		level=v
		hp*=level
		damage*=level
		speed+=level*10
var hp=3
var damage=1
var speed=300

var copy=false

# --------------------生命周期----------------------#
func _ready() -> void:
	target=get_tree().get_first_node_in_group('player')
	pass

func _physics_process(_delta: float) -> void:
	move()

# --------------------函数调用----------------------#
# 移动
func move():
	if target:
		dir=(target.position-self.position).normalized()
		velocity=dir*speed
		move_and_slide()

# 受伤
func getHurt(hurt):
	hp-=hurt
	flash()
	Main.action.run(
		{
			'obj':self,
			'name':'enemyHurt',
			'position':Vector2(0,0),
			'scale':scale
		}
	)
	if hp<=0:
		getDead()

# 闪烁 
func flash():
	body.material.set_shader_parameter('flashOpacity',1)
	await get_tree().create_timer(0.1).timeout
	body.material.set_shader_parameter('flashOpacity',0)

# 死亡
func getDead():
	Main.action.run(
		{
			'name':'enemyDead',
			'position':position,
		}
	)
	Main.drop.create(
		{
			'name':'gold',
			'position':position,
		}
	)
	target.getExp(level)
	queue_free()
